from django.views import View
from django.http import JsonResponse, HttpResponse
import json
from rest_framework.viewsets import ModelViewSet

from booktest.models import BookInfo, HeroInfo
from booktest.serializers_1 import BookInfoSerializer, HeroInfoSerializer
from .serializers_1 import BookInfoModelSerializer

"""
GET    /books/          提供所有记录
POST   /books/          新增一条记录
GET     /books/<pk>/    提供指定id的记录
PUT     /books/<pk>/    修改指定id的记录
DELETE  /books/<pk>/    删除指定id的记录
"""

class BookListView(View):
    """列表视图"""
    def get(self, requset):
        """查询所有图书"""
        #1. 查询出所有图书模型对象
        books = BookInfo.objects.all()  #此时查询出来的是字符集，不用try,也不会报错
        # 2.把模型转换json字典
        #定义一个列表
        book_list = []
        for book in books:
            book_dict = {
                'id' : book.id,
                'btitle' : book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment':book.bcomment,
                'image': book.image.url if book.image else ''


            }
            book_list.append(book_dict)
            #3. 响应对象
        return JsonResponse(book_list,safe=False)


    def post(self, request):
        #新增一本图书
        # 1.获取请求中的json数据
        json_bytes = request.body  #字节流
        json_str = json_bytes.decode()   #字节转字符串
        # 2. 把bytes类型的数据转换成json字典
        json_dict = json.loads(json_str)

        #3. 创建模型对象，赋值并存储到数据库
        book = BookInfo.objects.create(
            btitle=json_dict.get('btitle'),
            bpub_date= json_dict.get('bpub_date')
        )
        # 3.1 把新增的模型对象转换成json字典
        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }

        # 4.响应
        return JsonResponse(book_dict, status= 201)

class BookDetailView(View):
    """详细视图"""

    def get(self, request, pk):
        """查询单一"""
        ## 1.查询出pk所指定的那个数据
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        #2.把模型对象转换成字典
        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcmment': book.bcomment,
            'image': book.image.url if book.image else ''
         }
        #响应
        return JsonResponse(book_dict)

    def put(self, request, pk):
        """修改单一"""
        #获取前端传入的数据(校验)
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        # 获取出要修改的模型对象
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        #2.修改模型属性值
        book.btitle = json_dict.get('btitle')
        #3. 保存数据到数据库
        book.save()
        # 4. 把修改后的数据对象转换成字典
        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''

        }
        #响应
        return JsonResponse(book_dict)

    def delete(self, request, pk):
        """删除单一"""
        # 根据pk获取出要删除的模型对象
        try:
            book = BookInfo.objects.get(id = pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        book.delete()
        return HttpResponse(status=202)

class BookInfoViewSet(ModelViewSet):
    """定义视图集"""
    #指定序列化器

    serializer_class = BookInfoModelSerializer
    #指定查询
    queryset = BookInfo.objects.all()

# #查询单一
# book = BookInfo.objects.get(id = 1)
# #创建序列化器进行序列化器
# # 给instance参数传入实参  可以传模型/查询集(many=True)/字典
# # 构造序列化器对象
# # serializer = BookInfoSerializer(instance=book)
# serializer = BookInfoSerializer(book)
#
# serializer.data


#序列化查询集
# books = BookInfo.objects.all()
# serializer = BookInfoSerializer(books, many=True)
# # serializer = BookInfoSerializer({'book':books})
# serializer.data

#关联序列化
# hero = HeroInfo.objects.get(id= 1)
# serializer = HeroInfoSerializer(hero)
# serializer.data

# books = BookInfo.objects.get(id = 2)
# serializer = BookInfoSerializer(books)
# serializer.data


"""以下代码是进行反序列操作"""
from booktest.serializers_1 import BookInfoSerializer
data = {
    'btitle': '三国django',
    'bpub_date': '1991-11-11',
    'bread': 25,
    'bcmment':22
    }

serializers = BookInfoSerializer(data=data)
# serializers.is_valid(raise_exception=True)
# serializers.save()  #将校验后的数据修改到数据库
    #当序列化器调用save方法 ，会去执行序列化器中的create方法或update方法
